package org.ccay.async.impl;

import java.util.List;

import javax.inject.Named;

import org.springframework.beans.factory.InitializingBean;

import org.ccay.async.AsyncException;
import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.async.IMessageSender;
import org.ccay.async.conduit.AsyncConduit;
import org.ccay.async.conduit.ConduitSelector;
import org.ccay.async.conduit.DefaultConduitSelector;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;

/**
 * 异步处理器。
 * 向客户端屏蔽具体的异步机制。
 * 
 * 
 * @since Dec 6, 2011
 */
@Named
public class MessageSender implements InitializingBean, IMessageSender {
	
	/** 日志记录器 **/
	private final ILogger logger = CcayLoggerFactory.getLogger(MessageSender.class);
	
	/** 单例 **/
	private static IMessageSender instance;
	
	/**
	 * 获取一个AsyncHandler实例
	 * 
	 * 
	 * @since Dec 6, 2011
	 * @return
	 */
	public static IMessageSender getInstance() {
		return instance;
	}

	/** 异步通道选择器 **/
	private ConduitSelector selector;

	/**
	 * 设置异步通道选择器
	 * 
	 * @param selector
	 */
	public void setConduitSelector(ConduitSelector selector) {
		this.selector = selector;
	}

	/* (non-Javadoc)
	 * @see org.ccay.async.IAsyncMessageHandler#handle(org.ccay.async.AsyncMessage)
	 */
	public void send(AsyncMessage message) {
		if(message == null) {
			return;
		}
		
		logger.debug("AsyncMessage ready to send.");
		List<AsyncConduit> conduits = selector.select(message);
		if(conduits==null || conduits.isEmpty()) {
			throw new AsyncException("ccay.async.00010003",message.getType());
		}
		
		for (AsyncConduit conduit : conduits) {
			conduit.handle(message);
		}
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws ApplicationException {
		if(selector == null) {
			selector = new DefaultConduitSelector();
		}
		
		instance = this;
	}

	/* (non-Javadoc)
	 * @see org.ccay.async.IMessageSender#send(org.ccay.async.AsyncMessage, java.lang.String, org.ccay.async.IMessageProcessor)
	 */
	public void send(AsyncMessage message, String conduitName, IMessageProcessor processor) {
		
		
	}

}
